import axios from 'axios'
import { nanoid } from 'nanoid'

const personOptions = {
    namespaced: true,
    actions: {
        addPersonWang: function (context, personObj) {
            if (personObj.name.indexOf('王') === 0) {
                context.commit('ADD_PERSON', personObj)
            } else {
                alert("这个按钮只能添加姓王的人")
            }
        },
        addPersonServer(context) {
            axios.get('https://api.shadiao.pro/chp').then(
                (response) => {
                    context.commit('ADD_PERSON',{id:nanoid(),name:response.data.data.text})
                },
                (error) => {
                    alert(error.message)
                }
            )
        }
    },
    mutations: {
        ADD_PERSON(state, personObj) {
            if (personObj.name !== '') {
                state.personList.unshift(personObj)
            }
        }
    },
    state: {
        personList: [
            { id: "001", name: "张三" },
        ],
    },
    getters: {
        // 比如我现在在personOptions里，那这个state就是它自己的state，不需要state.state.personList
        firstPersonName: function (state) {
            return state.personList[0].name
        }
    },
}

export default personOptions